package com.akeil.flash.view;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.wb.swt.SWTResourceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.akeil.flash.action.DeleteDataAction;
import com.akeil.flash.action.OutputExcelAction;
//import com.akeil.flash.action.OutputTestInfoLimsAction;
import com.akeil.flash.action.OutputLimsAction;
import com.akeil.flash.action.QueryConditionAction;
import com.akeil.flash.contentprovider.DataContentProvider;
import com.akeil.flash.dataprocessing.IConstantProcessor;
import com.akeil.flash.dialog.ChangeContentDialog;
import com.akeil.flash.labelprovider.DataLabelProvider;
import com.akeil.flash.layout.AutoResizeTableLayout;
import com.akeil.flash.pojo.Data;
import com.akeil.flash.service.IDataService;
import com.akeil.flash.utils.DataStatisticsUtil;
import com.yang.serialport.utils.ByteUtils;

import flash.Activator;
import flash.Application;

@Component
public class HistoryDataView extends ViewPart {
	IPreferenceStore store = Activator.getDefault().getPreferenceStore();
	public static final String ID = "com.akeil.flash.view.HistoryDataView";
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	DecimalFormat df = new DecimalFormat("0.000000");
	DecimalFormat df_result = new DecimalFormat("0.00");
	@Autowired
	IDataService dataService;
	
	public static final String[] DATA_COLUMN_NAME = { "序号", "样品名称", "样品编号", "预置温度（℃）", "闪点（℃）", "测试时间" };
	TableColumn tableColumn = null;

	private TableViewer viewerData;
	private Table tableData;

	List<Data> datas = new ArrayList<Data>();
	
	private QueryConditionAction queryConditionAction;
	private OutputExcelAction outputExcelAction;
	private OutputLimsAction outputLimsAction;

	public HistoryDataView() {
	}

	public void createPartControl(Composite parent) {
		parent.setLayout(new FillLayout(SWT.HORIZONTAL));

		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new FormLayout());
		// 创建左上
		Composite compositeLeftTop = new Composite(container, SWT.NONE);
		FormData fd_compositeLeftTop = new FormData();
		fd_compositeLeftTop.top = new FormAttachment(0);
		fd_compositeLeftTop.left = new FormAttachment(0);
		fd_compositeLeftTop.bottom = new FormAttachment(100);
		fd_compositeLeftTop.right = new FormAttachment(100);
		compositeLeftTop.setLayoutData(fd_compositeLeftTop);
		// 创建一个区域的内容
		createLeftTopContent(compositeLeftTop);

		// 其他设置
		makeActions();
		initializeToolBar();
	}
	
	private void sendParameter(Data data){
		// 样品编号
		byte[] context = new byte[]{};
		byte[] bytes = null;
		byte[] newBytes = new byte[4];
		byte[] start = {(byte)0xaa,(byte)0x55,(byte)0x00};
		byte[] end = {(byte)0x00,(byte)0x00,(byte)0xcc,(byte)0x33,(byte)0xc3,(byte)0x3c};
		
		// 样品名称
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param2});
		bytes = data.getSampleno().getBytes();
		bytes = ByteUtils.addBytes(bytes,new byte[]{0,0,0,0,0,0,0,0});
		
		System.arraycopy(bytes, 0, newBytes, 0, 4);
		context = ByteUtils.addBytes(context,newBytes);
		
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param3});
		System.arraycopy(bytes, 4, newBytes, 0, 4);
		context = ByteUtils.addBytes(context,newBytes);		
		
		// 预置温度		
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param4});
		context = ByteUtils.addBytes(context,ByteUtils.floatTobyteArray(data.getPretemperature().floatValue()));
		
		// 闭口闪点		
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param5});
		context = ByteUtils.addBytes(context,ByteUtils.floatTobyteArray(data.getFlashtemperature().floatValue()));
		
		// 测试时间		
		bytes = data.getTesttime().getBytes();
		
		String testTime = data.getTesttime();
		String year = testTime.substring(0,4);
		String month = testTime.substring(5,7);
		String day = testTime.substring(8,10);
		String hour = testTime.substring(11,13);
		String mintue = testTime.substring(14,16);
		String second = testTime.substring(17,19);		
		
		String str = year+month+day+hour+mintue+second;
		bytes = str.getBytes();
		
		int d1 = Integer.parseInt(year);
		d1 <<= 16;
		d1 |= ((Integer.parseInt(month) & 0xFF) << 8);
		d1 |= ((Integer.parseInt(day)) & 0xFF);
		
		int d2 = Integer.parseInt(hour);
		d2 <<= 16;
		d2 |= ((Integer.parseInt(mintue) & 0xFF) << 8);
		d2 |= ((Integer.parseInt(second)) & 0xFF);
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param6});
		context = ByteUtils.addBytes(context,ByteUtils.intToByte(d1));
		
		context = ByteUtils.addBytes(context,new byte[]{IConstantProcessor.param7});
		context = ByteUtils.addBytes(context,ByteUtils.intToByte(d2));
		
		// 帧头，帧尾
		start[2] = (byte)context.length;
		context = ByteUtils.addBytes(start,context);
		context = ByteUtils.addBytes(context,end);
		
		Application.processor.sendParameter(context);
	}

	private void createLeftTopContent(Composite parent) {
		parent.setLayout(new GridLayout(3, false));
		viewerData = new TableViewer(parent, SWT.CHECK | SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		tableData = viewerData.getTable();
		tableData.setLinesVisible(true);
		tableData.setHeaderVisible(true);
		tableData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
		tableData.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		// / Popup Menu
		Menu contextMenu = new Menu(tableData);
		
		/*MenuItem printItem = new MenuItem(contextMenu, SWT.None);
		printItem.setEnabled(false);
		printItem.setText("打印数据");
		printItem.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/view/printer_16px.png").createImage());
		printItem.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				TableItem[] selections = tableData.getSelection();
				Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				ChangeContentDialog changeContentDialog = new ChangeContentDialog(parentShell);
				if(selections.length > 0){
					Data theData = (Data)selections[0].getData();
					sendParameter(theData);
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				
			}
		});
		*/
		MenuItem modifyItem = new MenuItem(contextMenu, SWT.None);
		modifyItem.setEnabled(false);
		modifyItem.setText("修改数据");
		modifyItem.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/view/modify_16px.png").createImage());
		modifyItem.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				TableItem[] selections = tableData.getSelection();
				Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
				ChangeContentDialog changeContentDialog = new ChangeContentDialog(parentShell);
				if(selections.length > 0){
					changeContentDialog.setTheData((Data)selections[0].getData());
					if(IDialogConstants.OK_ID == changeContentDialog.open()){
						dataService.updateByPrimayKey(changeContentDialog.getTheData());
						viewerData.refresh();
					}
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				
			}
		});
		
		tableData.setMenu(contextMenu);
		/*MenuItem limsItem = new MenuItem(contextMenu, SWT.None);
		limsItem.setEnabled(false);
		limsItem.setText("输出LIMS文件");
		limsItem.addSelectionListener(new SelectionListener() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				TableItem[] selections = tableData.getSelection();
				if (selections.length > 0) {
					List<Data> selectedDatas = new ArrayList<Data>();
					for (TableItem tableItem : selections) {
						Data exdata = (Data) tableItem.getData();
						selectedDatas.add(exdata);
					}

					OutputTestInfoLimsAction outputTestInfoLimisAction = new OutputTestInfoLimsAction(selectedDatas);
					outputTestInfoLimisAction.run();
				} else {

				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根

			}
		});*/
		
		MenuItem deleteItem = new MenuItem(contextMenu, SWT.None);
		deleteItem.setEnabled(false);
		deleteItem.setText("删除数据");
		deleteItem.setImage(AbstractUIPlugin.imageDescriptorFromPlugin(Activator.PLUGIN_ID, "icons/view/delete_16px.png").createImage());
		deleteItem.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				TableItem[] selections = tableData.getSelection();
				if(selections.length > 0){
					List<Data> selectedDatas = new ArrayList<Data>();
					for (TableItem tableItem : selections) {
						Data data = (Data)tableItem.getData();
						selectedDatas.add(data);
					}
					
					DeleteDataAction deleteDataAction = new DeleteDataAction();
					deleteDataAction.setDatas(selectedDatas);
					deleteDataAction.run();
					viewerData.setInput(DataStatisticsUtil.processIndex(dataService.selectDataToday()));
				}else{
					
				}
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO 自动生成的方法存根
				
			}
		});
		
		tableData.addListener(SWT.MouseDown, new Listener() {

			@Override
			public void handleEvent(Event event) {
				TableItem[] selections = tableData.getSelection();
				if(selections.length > 0){
					//printItem.setEnabled(true);
					modifyItem.setEnabled(true);
					//limsItem.setEnabled(true);
					deleteItem.setEnabled(true);
				}else{
					//printItem.setEnabled(false);
					modifyItem.setEnabled(false);
					//limsItem.setEnabled(false);
					deleteItem.setEnabled(false);
				}
			}
		});
		
		tableData.addMouseListener(new MouseAdapter() {
			   @Override
			   public void mouseDoubleClick(MouseEvent e) {
				   TableItem[] selections = tableData.getSelection();
				   if(selections.length > 0){
						Shell parentShell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
						ChangeContentDialog changeContentDialog = new ChangeContentDialog(parentShell);
						if(selections.length > 0){
							changeContentDialog.setTheData((Data)selections[0].getData());
							if(IDialogConstants.OK_ID == changeContentDialog.open()){
								dataService.updateByPrimayKey(changeContentDialog.getTheData());
								viewerData.refresh();
							}
						}
				   }
			   }
		});

		AutoResizeTableLayout layout_data_sequence = new AutoResizeTableLayout(viewerData.getTable());
		for (int i = 0; i < DATA_COLUMN_NAME.length; i++) {
			tableColumn = new TableColumn(viewerData.getTable(), SWT.LEFT);
			tableColumn.setText(DATA_COLUMN_NAME[i]);
			viewerData.getTable().getColumn(i).pack();
			if(i == 0 ){
				layout_data_sequence.addColumnData(new ColumnWeightData(20));
			}else if(i == 5){
				layout_data_sequence.addColumnData(new ColumnWeightData(100));
			}else{
				layout_data_sequence.addColumnData(new ColumnWeightData(50));
			}
		}
		viewerData.setContentProvider(new DataContentProvider());
		viewerData.setLabelProvider(new DataLabelProvider());
		// 设置数据

		//initData();
		// 1 查询所有的数据
		//datas = dataService.selectAll();
		// 2 查询今天的数据		
		//datas = dataService.selectDataToday();
		
		viewerData.setInput(DataStatisticsUtil.processIndex(datas));
	}

	private void colorItem(){
		TableItem[] items = tableData.getItems();
		if(items != null && items.length > 0){
			for (TableItem tableItem : items) {
				Data data = (Data)tableItem.getData();
				if(data.getStatus() == 3){
					tableItem.setBackground(new Color(null,20,255,20));
				}
			}
			
		}
	}
	
	private void makeActions() {
		queryConditionAction = new QueryConditionAction(this);
		outputExcelAction = new OutputExcelAction(viewerData);
		outputLimsAction = new OutputLimsAction(viewerData);
	}

	private void initializeToolBar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars().getToolBarManager();
		toolbarManager.add(queryConditionAction);
		toolbarManager.add(outputExcelAction);
		toolbarManager.add(outputLimsAction);
	}

	@Override
	public void dispose() {
		// TODO 自动生成的方法存根
		super.dispose();
	}

	@Override
	public void setFocus() {
		// TODO 自动生成的方法存根
	}
	
	public void refreshData(List<Data> datas){
		//重新计算Index
		viewerData.setInput(DataStatisticsUtil.processIndex(datas));
		colorItem();
	}
}